<?php
/**
 * Created by PhpStorm.
 * User: sqq
 * Date: 2018/07/11
 * Time: 上午10:11
 */

class ServiceController extends BaseController {

    /**
     * @Author:      sqq
     * @DateTime:    2018-07-11 10:12:29
     * @Description: 新建服务
     * desc格式：[
     *       "1.png",
     *       "2.png",
     *       "3.png"
     *  ]
     * @link: http://www.activity.com/ahp/ahp3.0/service/store?token=3de967e60c9bcd4b85a5858bac630b1c&service_name=%E6%97%B6%E5%BA%86%E5%BA%86%E6%B5%8B%E8%AF%95&classify=1&service_type=1&thumbnail=1.png&first_picture=1.png&desc=[%221.png%22,%222.png%22,%223.png%22]
     */
    public function store(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'service_name' => 'required',
                'classify' => 'required',
                'service_type' => 'required',
                'thumbnail' => 'required',
                'first_picture' => 'required',
                'desc' => 'required',
                'start_num' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }

            $time = date("Y-m-d H:i:s",time());
            $service = new AhpService();
            $service->service_name = Input::get("service_name");
            $service->classify = Input::get("classify",1);
            $service->service_type = Input::get("service_type",1);
            $service->thumbnail = Input::get("thumbnail");
            $service->first_picture = Input::get("first_picture");
            $service->title = Input::get("title");
            $service->content = Input::get("content");
            $service->status = 2;
            $service->is_recommend = 2;
            $service->created_at = $time;
            $service->created_by = $mkt_user->id;
            $service->updated_at = $time;
            $service->updated_by = $mkt_user->id;
            $service->start_num = Input::get('start_num');

            if($service->save()){
                $desc = Input::get("desc");
                if($desc){
                    if(!is_array($desc)){
                        $desc = json_decode($desc,true);
                    }
                    foreach($desc as $_val){
                        $service_desc = new AhpServiceDesc();
                        $service_desc->service_id = $service->id;
                        $service_desc->desc = $_val;
                        $service_desc->created_at = $time;
                        $service_desc->updated_at = $time;
                        $service_desc->save();
                    }
                }
            }

            $response = array('code' => 0, 'msg' => 'ok');

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/store", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-11 12:55:29
     * @Description: 修改服务
     * desc格式：[
     *       "1.png",
     *       "2.png",
     *       "3.png"
     *  ]
     * @link: http://www.activity.com/ahp/ahp3.0/service/edit?token=3de967e60c9bcd4b85a5858bac630b1c&service_name=%E6%97%B6%E5%BA%86%E5%BA%86%E6%B5%8B%E8%AF%95&classify=1&service_type=1&thumbnail=1.png&first_picture=1.png&desc=[%221.png%22,%222.png%22,%223.png%22]&id=1
     */
    public function edit(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'service_name' => 'required',
                'classify' => 'required',
                'service_type' => 'required',
                'thumbnail' => 'required',
                'first_picture' => 'required',
                'desc' => 'required',
                'start_num' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }

            $time = date("Y-m-d H:i:s",time());
            $service = AhpService::where("id",Input::get("id"))->first();
            $service->service_name = Input::get("service_name");
            $service->classify = Input::get("classify",1);
            $service->service_type = Input::get("service_type",1);
            $service->thumbnail = Input::get("thumbnail");
            $service->first_picture = Input::get("first_picture");
            $service->title = Input::get("title");
            $service->content = Input::get("content");
            $service->created_at = $time;
            $service->created_by = $mkt_user->id;
            $service->updated_at = $time;
            $service->updated_by = $mkt_user->id;
            $service->start_num = Input::get('start_num');

            if($service->save()){
                AhpServiceDesc::where("service_id",Input::get("id"))->delete();
                $desc = Input::get("desc");
                if($desc){
                    if(!is_array($desc)){
                        $desc = json_decode($desc,true);
                    }
                    foreach($desc as $_val){
                        $service_desc = new AhpServiceDesc();
                        $service_desc->service_id = $service->id;
                        $service_desc->desc = $_val;
                        $service_desc->created_at = $time;
                        $service_desc->updated_at = $time;
                        $service_desc->save();
                    }
                }
            }

            $response = array('code' => 0, 'msg' => 'ok');

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/edit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-11 13:27:37
     * @Description: 服务详情
     * @link: http://www.activity.com/ahp/ahp3.0/service/show?token=e28f23575e72201b3a1144955566a46d&id=1
     */
    public function show(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }

            $response = AhpService::with("desc")->where("id",Input::get("id"))->first();
            if(!is_null($response)){
                $response->thumbnail = Config::get('config.ahp_upload_files_url').$response->thumbnail;
                $response->first_picture = Config::get('config.ahp_upload_files_url').$response->first_picture;
                $response->img_url = Config::get('config.ahp_upload_files_url');
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $response);

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/edit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
    * @Author:      sqq
    * @DateTime:    2018-07-11 14:44:37
    * @Description: 服务列表-服务分类
    * @link: http://www.activity.com/ahp/ahp3.0/service/service_classify?token=3de967e60c9bcd4b85a5858bac630b1c
    */
      public function service_classify(){
          $validator = Validator::make(Input::all(),
              array(
                  'token' => 'required',
              )
          );
          $response = array('code' => 0, 'msg' => 'ok');
          do{
              if($validator->fails()) {
                  $response = Lang::get("ahp_error.args_error_1000");
                  $response["result"]=$validator->messages()->all();
                  break;
              }
              $mkt_user=$this->verificationAhpUserToken(Input::get("token"),$response);
              if(is_null($mkt_user)){
                  break;
              }

//              $response = AhpServiceClassify::where("status",1)
//                  ->orderBy("sort","asc")
//                  ->select("id","name")
//                  ->get();
              $response = ProductClassification::get();

              $response = array('code' => 0, 'msg' => 'ok', 'result' => $response);

          }while(false);
          Log::info("info", array("system" => "ahp" ,"event" => "/service/service_classify", 'input' =>Input::all() ,"output" => $response));
          return json_encode($response);
      }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-11 13:18:37
     * @Description: 服务列表
     * @link: http://www.activity.com/ahp/ahp3.0/service/index?token=3de967e60c9bcd4b85a5858bac630b1c&page=1&page_size=10
     */
    public function index(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ahp_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ahp_user)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);

            $res = AhpService::with('ahp_users')->orderBy('id','desc');

            //大分类
            if(Input::get('classify')){
                $res->where('classify',Input::get('classify'));
            }

            //投放状态
            if(Input::get('status')){
                $res->where('status',Input::get('status'));
            }

            //推荐状态
            if(Input::get('is_recommend')){
                $res->where('is_recommend',Input::get('is_recommend'));
            }

            //包类型
            if(Input::get('service_type')){
                $res->where('service_type',Input::get('service_type'));
            }

            //服务名称
            if(Input::get('service_name')){
                $res->where('service_name','like','%'.Input::get('service_name').'%');
            }





//            if(Input::get('begin_data') && Input::get('end_data')){
//                $res->whereBetween('created_at',array(Input::get('begin_data').' 00:00:00',Input::get('end_data').' 23:59:59'));
//            }
            $count = $res->count();
            $res=$res->skip($page_size*($page-1))->take($page_size)->get();

            if(!is_null($res)){
                foreach($res as $key => $val){
                    $val->ahp_upload_files_url = Config::get('config.ahp_upload_files_url').$val->thumbnail;
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"serviceList"=>$res));

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/index", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-11 15:51:37
     * @Description: 服务列表-服务投放
     * @link: http://www.activity.com/ahp/ahp3.0/service/editServiceStatus?token=3de967e60c9bcd4b85a5858bac630b1c&id=1&status=1
     */
    public function editServiceStatus(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "id"=>'required',
                "status"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ahp_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ahp_user)){
                break;
            }

            //判断当前服务是否有配置项（判断是否有包id存在，mkt的包或者cms的包）


            $res = AhpServiceMktCms::where('service_id',Input::get("id"))->first();
            if(is_null($res)){
                $response = Lang::get("ahp_error.service_not_exit_error_9000");
                break;
            }
            AhpService::where('id',Input::get("id"))->update(array("status" => Input::get("status")));

            $response = array('code' => 0, 'msg' => 'ok');

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/editServiceStatus", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-11 17:13:37
     * @Description: 服务列表-服务推荐
     * @link: http://www.activity.com/ahp/ahp3.0/service/editRecommend?token=3de967e60c9bcd4b85a5858bac630b1c&id=1&is_recommend=1
     */
    public function editRecommend(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "id"=>'required',
                "is_recommend"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ahp_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ahp_user)){
                break;
            }

            //判断当前服务是否有配置项（判断是否有包id存在，mkt的包或者cms的包）


            $res = AhpService::where('id',Input::get("id"))->first();
            if(!is_null($res)){
                if($res->status == 2){
                    $response = Lang::get("ahp_error.service_status_not_exit_error_9001");
                    break;
                }
                AhpService::where('id',Input::get("id"))->update(array("is_recommend" => Input::get("is_recommend")));
            }

            $response = array('code' => 0, 'msg' => 'ok');

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/editRecommend", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-14 12:26:37
     * @Description: 服务详情-服务适配-活动包列表
     * @link: http://www.activity.com/ahp/ahp3.0/service/lists?token=3de967e60c9bcd4b85a5858bac630b1c&service_type=1&name=%E8%B5%A4%E5%B3%B0
     */
    public function lists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "service_type"=>'required',
                "service_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ahp_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ahp_user)){
                break;
            }

            //获取参数
            $service_type = Input::get("service_type");
            $service_id = Input::get("service_id");
            $name = Input::get("name");

            if($service_type == 1){ //mkt 活动包
                $now_time = date("Y-m-d H:i:s",time());
                $lists = ProductActivity::where("status",1)
                    //->where("type",1)
                    ->where("begin_time",'<=',$now_time)
                    ->where("end_time",'>=',$now_time);
                if($name){
                    $lists = $lists->where('name','like','%'.$name.'%');
                }
            }else{
                //cms 基础包
                $lists = ProductPackage::where("status",1)->where('place',2);
                if($name){
                    $lists = $lists->where('name','like','%'.$name.'%');
                }
                //$ppc=ProductPackageCity::where("city_id",$sc_user->shop->city_id)->where("status",1)->select("pack_id")->get()->toArray();
                //$pp=ProductPackage::whereIn("id",$ppc)->where('status',1)->where('place',2)->select('id','name','desc')->orderBy("sort","ASC")->get();
            }



            //判断是否已经适配，已经适配的不展示
            $mkt_cms_id = AhpServiceMktCms::where('type',$service_type)->where('service_id',$service_id)->select('mkt_cms_id')->get();

            if(!empty($mkt_cms_id)){
                $mkt_cms_id = array_column($mkt_cms_id->toArray(),'mkt_cms_id');
                $lists = $lists->whereNotIn('id',$mkt_cms_id);
            }

            $lists = $lists->select("id","status","name")->orderBy("id","ASC")->get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $lists);

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-14 12:26:37
     * @Description: 服务详情-服务适配-适配服务包-活动包-添加
     * @link: http://www.activity.com/ahp/ahp3.0/service/addServiceProduct?token=3de967e60c9bcd4b85a5858bac630b1c&service_type=1&service_id=1&mkt_cms_id=64
     */
    public function addServiceProduct(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "service_type"=>'required',
                "service_id"=>'required',
                "mkt_cms_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ahp_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ahp_user)){
                break;
            }

            //获取参数
            $service_type = Input::get("service_type");
            $service_id = Input::get("service_id");
            $mkt_cms_id = Input::get("mkt_cms_id");
            $res = AhpServiceMktCms::where("type",$service_type)->where("service_id",$service_id)->where("mkt_cms_id",$mkt_cms_id)->first();
            if(is_null($res)){
                $ahp_mkt_cms = new AhpServiceMktCms();
                $ahp_mkt_cms->type = $service_type;
                $ahp_mkt_cms->service_id = $service_id;
                $ahp_mkt_cms->mkt_cms_id = $mkt_cms_id;
                $ahp_mkt_cms->created_at = date("Y-m-d H:i:s",time());
                $ahp_mkt_cms->save();
            }else{
                $response = Lang::get("ahp_error.ahp_service_mkt_cms_add_not_exist_30011");
                break;
            }

            $response = array('code' => 0, 'msg' => 'ok');

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/addServiceProduct", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-14 15:29:37
     * @Description: 服务详情-服务适配-适配服务包-活动包-删除
     * @link:
     */
    public function deleteServiceProduct(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "service_type"=>'required',
                "service_id"=>'required',
                "mkt_cms_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ahp_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ahp_user)){
                break;
            }

            //获取参数
            $service_type = Input::get("service_type");
            $service_id = Input::get("service_id");
            $mkt_cms_id = Input::get("mkt_cms_id");
            $res = AhpServiceMktCms::where("type",$service_type)->where("service_id",$service_id)->where("mkt_cms_id",$mkt_cms_id)->first();
            if(!is_null($res)){
                AhpServiceMktCms::where("type",$service_type)->where("service_id",$service_id)->where("mkt_cms_id",$mkt_cms_id)->delete();

                AhpServiceClassification::where('service_id',$service_id)->where('status',1)->delete();
            }else{
                $response = Lang::get("ahp_error.ahp_service_mkt_cms_delete_not_exist_30012");
                break;
            }

            $response = array('code' => 0, 'msg' => 'ok');

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/deleteServiceProduct", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-14 15:41:37
     * @Description: 服务适配-分类列表
     * @link: http://www.activity.com/ahp/ahp3.0/service/typeLists?token=3de967e60c9bcd4b85a5858bac630b1c&service_type=2&service_id=2
     */
    public function typeLists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "service_id"=>'required',
                "service_type"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ahp_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ahp_user)){
                break;
            }

            //获取参数
            $service_id = Input::get("service_id");
            $service_type = Input::get("service_type");
            $mkt_cms = AhpServiceMktCms::where("type",$service_type)->where("service_id",$service_id)->select("mkt_cms_id")->get();
            $product_pack_item = [];
            if(!is_null($mkt_cms)){
                //获取适配的活动包id
                $mkt_cms = array_column($mkt_cms->toArray(), 'mkt_cms_id');
                //根据活动包id获取产品包id
                if($mkt_cms){
                    if($service_type == 1){ //mkt
                        $pap=ProductActivityPackage::leftJoin("product_package","product_activity_package.package_id","=","product_package.id")
                            ->whereIn('product_activity_id',$mkt_cms)
                            ->distinct('package_id')
                            ->groupBy('package_id')
                            ->select('package_id','product_activity_package.id','product_package.name')->get();
                        header("Content-type:text/html;charset=utf-8");
                        if (!empty($pap)){
                            foreach ($pap as $value){
                                $product_pack_item = ProductPackItem::leftjoin("supply_classification","supply_classification.id","=","product_pack_item.item_id" )
                                    ->where("pack_id",$value->package_id)
                                    ->where("type",3)
                                    ->where("product_pack_item.status",1)
                                    ->distinct('product_pack_item.item_id')
                                    ->select("supply_classification.name","product_pack_item.item_id")
                                    ->get();
                                $value->product_pack_item = $product_pack_item;
                            }
                            //$value->id => product_activity_package_id
                        }else{
                            $product_pack_item = '';
                        }
                    }else{
                        //cms
                        $product_pack_item = ProductPackItem::leftjoin("supply_classification","supply_classification.id","=","product_pack_item.item_id" )
                            ->whereIn("pack_id",$mkt_cms)
                            ->where("type",3)
                            ->where("product_pack_item.status",1)
                            ->distinct('product_pack_item.item_id')
                            ->select("supply_classification.name","product_pack_item.item_id")
                            ->groupBy("product_pack_item.item_id")
                            ->get();
                    }
                }else{
                    $product_pack_item = '';
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $product_pack_item);

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/typeLists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-16 12:47:37
     * @Description: 服务适配-适配
     * @@param:  data       Json
     * {
     *       "service_id":1,
     *       "desc":{
     *           "0":{
     *               "service_mkt_cms_id":7,
     *               "desc":{
     *                   "0":"1111",
     *                   "1":"22222"
     *               }
     *           },
     *           "1":{
     *               "service_mkt_cms_id":64,
     *               "desc":{
     *                   "0":"哈哈哈",
     *                   "1":"额鹅鹅鹅"
     *                }
     *           }
     *       },
     *       "adaptation":{
     *           "0":48,
     *           "1":2425
     *       }
     *}
     * @link: http://www.activity.com/ahp/ahp3.0/service/setAuth?token=3de967e60c9bcd4b85a5858bac630b1c&data={%20%22service_id%22:%201,%20%22service_mkt_cms_id%22:%207,%20%22desc%22:%20{%20%220%22:%20%221111%22,%20%221%22:%20%2222222%22%20},%20%22adaptation%22:%20{%20%220%22:%2048,%20%221%22:%202425%20}%20}
     */
    public function setAuth(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "data"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ahp_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ahp_user)){
                break;
            }

            //获取参数
            $data = Input::get('data');
            if(!is_array($data)){
                $data = json_decode($data,true);
            }
            DB::beginTransaction();
            if($data){
                try{
                    if(isset($data['desc'])){
                        foreach($data['desc'] as $_key => $_val){
                            AhpServiceMktCmsDesc::where("status",1)->where("service_mkt_cms_id",$_val['service_mkt_cms_id'])->delete();
                            foreach($_val['desc'] as $key => $val){
                                $desc = new AhpServiceMktCmsDesc();
                                $desc->service_mkt_cms_id = $_val['service_mkt_cms_id'];
                                $desc->desc = $val;
                                $desc->status = 1;
                                $desc->created_at = date("Y-m-d H:i:s",time());
                                $desc->updated_at = date("Y-m-d H:i:s",time());
                                $desc->save();
                            }
                        }
                    }
                }catch(Exception $e){
                    Log::error("error", array("system" => "ahp3.0", "event" => "setAuth", 'input' => Input::all(), "exception" => $e));
                    DB::rollBack();
                    $response = array('code' => -1, 'msg' => '保存服务失败');
                    break;
                }

                try {
                    AhpServiceClassification::where("status",1)->where("service_id",$data['service_id'])->delete();
                    if(isset($data['adaptation'])){
                        foreach($data['adaptation'] as $key => $val){
                            $desc = new AhpServiceClassification();
                            $desc->service_id = $data['service_id'];
                            $desc->item_id = $val;
                            $desc->status = 1;
                            $desc->created_at = date("Y-m-d H:i:s",time());
                            $desc->updated_at = date("Y-m-d H:i:s",time());
                            $desc->save();
                        }
                    }
                }catch(Exception $e){
                        Log::error("error", array("system" => "ahp3.0", "event" => "setAuth", 'input' => Input::all(), "exception" => $e));
                        DB::rollBack();
                        $response = array('code' => -1, 'msg' => '保存服务失败');
                        break;
                    }
                }

                try {
                    if(isset($data['isdefualt'])){
                        $rs = AhpServiceIsdefualt::where('status',1)->where('service_id',$data['service_id'])->first();
                        if(is_null($rs)){
                            $rs = new AhpServiceIsdefualt();
                            $rs->created_at = Common::currentTimeString();
                        }
                        $rs->service_id = $data['service_id'];
                        $rs->item_id = $data['isdefualt'];
                        $rs->status = 1;
                        $rs->updated_at = Common::currentTimeString();
                        $rs->save();
                    }
                }catch(Exception $e){
                    Log::error("error", array("system" => "ahp3.0", "event" => "setAuth", 'input' => Input::all(), "exception" => $e));
                    DB::rollBack();
                    $response = array('code' => -1, 'msg' => '保存服务失败');
                    break;
                }
            DB::commit();

            $response = array('code' => 0, 'msg' => 'ok');

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/setAuth", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-16 14:40:29
     * @Description: 服务适配-页面加载
     * @link:  http://www.activity.com/ahp/ahp3.0/service/setAuth_onload?token=3de967e60c9bcd4b85a5858bac630b1c&service_id=1&service_type=1
     */
    public function setAuth_onload(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "service_id"=>'required',
                "service_type"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ahp_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ahp_user)){
                break;
            }

            //获取参数
            $service_id = Input::get('service_id');
            $service_type = Input::get('service_type');

            //查询基础信息
            $ahp_service = AhpService::join("product_classification","ahp_service.classify","=","product_classification.id")->where("ahp_service.id",$service_id)->select("ahp_service.id","service_name","name","service_type","thumbnail","first_picture","title","content")->first();

            if(!empty($ahp_service)){
                $ahp_service->img_url = Config::get('config.ahp_upload_files_url');

                //查询服务项目
                if($service_type == 1){
                    //mkt
                    $ahp_service->service = AhpServiceMktCms::join("product_activity","ahp_service_mkt_cms.mkt_cms_id","=","product_activity.id")->where("ahp_service_mkt_cms.type",$service_type)->where("service_id",$service_id)->with("mkt_cms_desc")->select("product_activity.id","product_activity.name","ahp_service_mkt_cms.id as ids","ahp_service_mkt_cms.mkt_cms_id","product_activity.status")->get();
                }else{
                    //cms
                    $ahp_service->service = AhpServiceMktCms::join("product_package","ahp_service_mkt_cms.mkt_cms_id","=","product_package.id")->where("ahp_service_mkt_cms.type",$service_type)->where("service_id",$service_id)->with("mkt_cms_desc")->select("product_package.id","product_package.name","ahp_service_mkt_cms.id as ids","ahp_service_mkt_cms.mkt_cms_id","product_package.status")->get();
                }

                //根据活动包id/产品包id获取对应的耗材分类
                $mkt_cms = array_column($ahp_service->service->toArray(), 'mkt_cms_id');
                //根据活动包id获取产品包id
                if($mkt_cms){
                    if($service_type == 1){ //mkt
                        $pap=ProductActivityPackage::leftJoin("product_package","product_activity_package.package_id","=","product_package.id")
                            ->whereIn('product_activity_id',$mkt_cms)
                            ->distinct('package_id')
                            ->groupBy('package_id')
                            ->select('package_id','product_activity_package.id','product_package.name')->get();
                        if (!empty($pap)){
                            $pap = $pap->toArray();
                            $package_id = array_column($pap,'package_id');
                            //foreach ($pap as $value){
                                $product_pack_item = ProductPackItem::leftjoin("supply_classification","supply_classification.id","=","product_pack_item.item_id" )
                                    //->where("pack_id",$value['package_id'])
                                    ->whereIn("pack_id",$package_id)
                                    ->where("type",3)
                                    ->where("product_pack_item.status",1)
                                    ->distinct('product_pack_item.item_id')
                                    ->select("supply_classification.name","product_pack_item.item_id")
                                    ->get()->toArray();
                                $ahp_service->product_pack_item = $product_pack_item;
                           // }
                            //$value->id => product_activity_package_id
                        }else{
                            $ahp_service->product_pack_item = '';
                        }
                    }else{
                        //cms
                        $ahp_service->product_pack_item = ProductPackItem::leftjoin("supply_classification","supply_classification.id","=","product_pack_item.item_id" )
                            ->whereIn("pack_id",$mkt_cms)
                            ->where("type",3)
                            ->where("product_pack_item.status",1)
                            ->distinct('product_pack_item.item_id')
                            ->select("supply_classification.name","product_pack_item.item_id")
                            ->groupBy("product_pack_item.item_id")
                            ->get();

                    }
                    if(!empty($ahp_service->product_pack_item)){
                        $a = $ahp_service->product_pack_item ;
                        foreach($a as $key => $val){
                            $status = AhpServiceClassification::where('item_id',$val['item_id'])->where('service_id',$service_id)->where('status',1)->first();
                            if(!empty($status)){
                                $a[$key]['status'] = 1;
                            }else{
                                $a[$key]['status'] = 2;
                            }

                            $a[$key]['isdefualt'] = 2;
                            $rs = AhpServiceIsdefualt::where('item_id',$val['item_id'])->where('service_id',$service_id)->where('status',1)->first();
                            if(!is_null($rs)){
                                $a[$key]['isdefualt'] = 1;
                            }

                            $ahp_service->product_pack_item = $a;
                        }
                    }
                }else {
                    $ahp_service->product_pack_item = '';
                }
            }


            $response = array('code' => 0, 'msg' => 'ok', 'result' => $ahp_service);

        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "/service/setAuth_onload", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

}